package com.sam.scanner.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mobilerecognition.engine.RecogResult;
import com.mobilerecognition.phonenumer.ui.ScanerActivity;
import com.mobilerecognition.phonenumer.utils.Tools;
import com.sam.scanner.R;
import com.sam.scanner.bean.ExBean;
import com.sam.scanner.bean.OrderCompanyBean;
import com.sam.scanner.bean.OrderScanerDataBean;
import com.sam.scanner.bean.ScanBean;
import com.sam.scanner.utils.HTTPCallBack;
import com.sam.scanner.utils.Utils;
import com.sam.scanner.utils.SharedPreferencesUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ScanerMainActivity extends ScanerActivity implements TextWatcher {

    ImageView mFlashImage;
    LinearLayout bottomView;
    TextView btn_close_scaner, btn_ok_in;
    View popView;
    TextView tv_goods_num;
    EditText et_ex_ps_name,
            et_ex_ps_phone_num,
            et_goods_num,
            et_order_name,
            et_order_num,
            et_phone_name,
            et_phone_num,
            et_address_num;
    TextView tv_toobar_title;
    TextView btn_re_start_scaner,
            tv_get_package_num,
            et_package_num,
            btn__hh_re_start_scaner;
    Switch  switch_is_smms;

    boolean isOpen = false;
    int tag = 1;        // 1快递员 2代办点 3同时使用

    ArrayList<ScanBean> scanList = new ArrayList<>();
    AlertDialog dialog;
    AlertDialog.Builder builder;

    String exName = "";  //快递员姓名
    String exPhoneNum = ""; //快递员手机号
    String goodsNum = ""; // 货号
    String orderComName = ""; //快递公司名字
    String orderNum = ""; //快递单号
    String userName = ""; //用户名字
    String userPhoneNum = ""; //用户手机号
    String address = ""; //放置地址

    int localPackAgeNum = 0 ;
    int packAgeNum = 0;   //快递件数


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tag = getIntent().getIntExtra("scanerTag", -1);
        exName = getIntent().getStringExtra("exName");
        exPhoneNum = getIntent().getStringExtra("exPhoneNum");
        address = getIntent().getStringExtra("address");
        RelativeLayout topView = (RelativeLayout) getLayoutInflater().inflate(R.layout.view_activity_top_bar_mb, null, false);
        topView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, Tools.dip2px(getApplicationContext(), 88)));
        mFlashImage = topView.findViewById(R.id.iv_flash);
        setTopMargin(48);
        addView2Root(topView);

        topView.findViewById(R.id.btn_msm_mb).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), "短信模板点击选择", Toast.LENGTH_LONG).show();
            }
        });
        String tmplocalPackAgeNum = SharedPreferencesUtil.getInstance().getSP("localPackAgeNum");
        if (tmplocalPackAgeNum!=null && !tmplocalPackAgeNum.equals("")) {
            localPackAgeNum = Integer.valueOf(tmplocalPackAgeNum);
        }
        tv_toobar_title = findViewById(R.id.tv_toobar_title);
        bottomView = (LinearLayout) getLayoutInflater().inflate(R.layout.view_activity_bottom, null, false);
        bottomView.setLayoutParams(new LinearLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, Tools.dip2px(getApplicationContext(), 55)));
        addView2BottomLayout(bottomView);

        btn_ok_in = bottomView.findViewById(R.id.btn_ok_in);
        btn_close_scaner = bottomView.findViewById(R.id.btn_close_scaner);
        // 1快递员 2代办点 3同时使用
        if (tag == 1) {
            tv_toobar_title.setText("扫描");
            btn_ok_in.setText("确认放置");
            btn_close_scaner.setText("结束扫描");
        } else {
            tv_toobar_title.setText("入库");
            btn_ok_in.setText("确定入库");
            btn_close_scaner.setText("结束入库");
        }
        btn_ok_in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //判断是否完整性
                okScanerNext();
            }
        });
        btn_close_scaner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (tag == 3) {
                    startActivity(new Intent(getApplicationContext(), InPackageRecordActivity.class));
                } else {
                    if(scanList.size() == 0 ){
                        finish();
                    }else {
                        inPackage();
                    }
                }
            }
        });

        mFlashImage.setOnClickListener(view -> {
            isOpen = !isOpen;
            openFlash(isOpen);
            mFlashImage.setImageResource(isOpen ? R.drawable.flash_off_y : R.drawable.flash_on_y);
        });
        findViewById(R.id.tv_back).setOnClickListener(view -> finish());
        if (popView == null) {
            popView = LayoutInflater.from(this).inflate(R.layout.view_activity_scaner, null);
            tv_get_package_num = popView.findViewById(R.id.tv_get_package_num);

            // 1快递员 2代办点 3同时使用
            switch (tag) {
                case 1://快递员
                    popView.findViewById(R.id.ll_goods_num).setVisibility(View.GONE);
                    popView.findViewById(R.id.ll_package_num).setVisibility(View.VISIBLE);
                    popView.findViewById(R.id.ll_ex_num).setVisibility(View.GONE);
                    popView.findViewById(R.id.ll_address_num).setVisibility(View.VISIBLE);
                    break;
                case 2:
                    popView.findViewById(R.id.ll_ex_num).setVisibility(View.GONE);
                    break;
                case 3:
                    popView.findViewById(R.id.ll_ex_num).setVisibility(View.VISIBLE);
                    tv_get_package_num.setVisibility(View.VISIBLE);

                    break;
            }

            popView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            int width = popView.getMeasuredWidth();
            int height = popView.getMeasuredHeight();
            popView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height));
//            addView2BottomLayout(popView, 0);
            setContentLayoutAndPadding(popView);
            et_goods_num = popView.findViewById(R.id.et_goods_num);
            et_order_name = popView.findViewById(R.id.et_order_name);
            switch_is_smms = popView.findViewById(R.id.switch_is_smms);
            et_order_num = popView.findViewById(R.id.et_order_num);
            et_package_num = popView.findViewById(R.id.et_package_num);
            et_phone_name = popView.findViewById(R.id.et_phone_name);
            et_phone_num = popView.findViewById(R.id.et_phone_num);
            tv_goods_num = popView.findViewById(R.id.tv_goods_num);
            et_address_num = popView.findViewById(R.id.et_address_num);
            btn_re_start_scaner = popView.findViewById(R.id.btn_re_start_scaner);
            btn__hh_re_start_scaner = popView.findViewById(R.id.btn__hh_re_start_scaner);
            et_ex_ps_name = popView.findViewById(R.id.et_ex_ps_name);
            et_ex_ps_phone_num = popView.findViewById(R.id.et_ex_ps_phone_num);
            btn_re_start_scaner.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    initScaner();
                    scrollToView(1);
                }
            });
            btn__hh_re_start_scaner.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    initScaner();
                    scrollToView(1);
                }
            });
            et_phone_num.addTextChangedListener(this);
            et_address_num.addTextChangedListener(this);
            et_ex_ps_name.addTextChangedListener(this);
            et_ex_ps_phone_num.addTextChangedListener(this);
            et_order_name.addTextChangedListener(this);
            et_order_num.addTextChangedListener(this);
            et_phone_name.addTextChangedListener(this);
            et_address_num.addTextChangedListener(this);
        }
        et_ex_ps_name.setText(exName);
        et_ex_ps_phone_num.setText(exPhoneNum);

        btn_ok_in.setBackgroundColor(getResources().getColor(R.color.unenabled));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        openFlash(false);
    }

    @Override
    protected void outTimeWarning() {

    }

    public void setScanText(String text) {
        mQrCodeFinderView.setScanText(text);
    }


    @Override
    protected void handlerRes(RecogResult result, Bitmap bmImage) {
        super.handlerRes(result, bmImage);
        if (!lineNum.equals("")) {
            if (phoneNum.equals("")) {
                getOrderCom(lineNum);
            }
            Log.i("SamTam", "订单号: " + lineNum + (phoneNum.equals("") ? " 识别手机号中... " : "  手机号: " + phoneNum));
            setScanText("订单号: " + lineNum + (phoneNum.equals("") ? " 识别手机号中... " : "  手机号: " + phoneNum));
            setGoodsNum(lineNum, phoneNum);
            showBtnStatus();
        }

    }

    private void showTestBitmap(boolean isShow, Bitmap bitmap) {
        findViewById(R.id.iv_test_bitmap).setVisibility(isShow ? View.VISIBLE : View.GONE);
        if (isShow) {
//            ((ImageView)findViewById(R.id.iv_test_bitmap)).setImageBitmap(bitmap);
        }
    }


    private void showExListDialog(ExBean exBean) {
        if (exBean.getShippers().size() == 1) {
            et_order_name.setText(exBean.getShippers().get(0).getShipperName());
            et_order_name.setTag(exBean.getShippers().get(0).getShipperCode());
        } else {
            if (exBean.getShippers().size() > 0) {
                String items[] = new String[exBean.getShippers().size()];
                for (int i = 0; i < exBean.getShippers().size(); i++) {
                    items[i] = exBean.getShippers().get(i).getShipperName();
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setCancelable(false);
                builder.setTitle("选择快递公司");
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        et_order_name.setText(exBean.getShippers().get(which).getShipperName());
                        et_order_name.setTag(exBean.getShippers().get(which).getShipperCode());
                        showBtnStatus();
                    }
                });
                if (dialog == null) {
                    dialog = builder.create();
                }
                if (!dialog.isShowing()) {
                    dialog.show();
                }

            }
        }


    }


    private void setGoodsNum(String orNum, String phNum) {
        et_phone_num.setText(phNum);
        et_order_num.setText(orNum);
        orderNum = orNum;
        userPhoneNum = phNum;
        initGoodsNum();
        showPackAgeNum();
    }

    private void showPackAgeNum() {
        if (tv_get_package_num != null) {
            tv_get_package_num.setText("集件包裹数:" + packAgeNum);
        }
        if (et_package_num != null) {
            et_package_num.setText(packAgeNum + "");
        }
    }


    public String convertTimestamp2Date(Long timestamp, String pattern) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(new Date(timestamp));
    }

    private boolean checkIsInputSuc() {
        orderComName = et_order_name.getText().toString();
        orderNum = et_order_num.getText().toString();
        exName = et_ex_ps_name.getText().toString();
        goodsNum = et_goods_num.getText().toString();
        userName = et_phone_name.getText().toString();
        userPhoneNum = et_phone_num.getText().toString();
        address = et_address_num.getText().toString();
        if (userName.equals("")) {
            if (userPhoneNum.length() == 11) {
                String userNameT = SharedPreferencesUtil.getInstance().getSP(userPhoneNum);
                Log.i("SamTam", userNameT);
                if (userNameT != null && userNameT.length() > 0) {
                    et_phone_name.post(() -> et_phone_name.setText(userNameT));
                }
            }
        }

        int isSuc = 0;
        if (orderNum.equals("") || orderComName.equals("") || userPhoneNum.length() < 11 || userName.equals("") || userPhoneNum.equals("")) {
            isSuc++;
        }
        switch (tag) {
            case 1://快递员
                if (address.equals("")) {
                    isSuc++;
                }
                break;
            case 2://代办点
                if (goodsNum.equals("")) {
                    isSuc++;
                }
                break;
            case 3://同时
                if (goodsNum.equals("") || exName.equals("") || exPhoneNum.equals("") || exPhoneNum.length() < 11) {
                    isSuc++;
                }
                break;
        }
        return isSuc > 0 ? false : true;
    }

    /**
     * 生成货号
     */
    private void initGoodsNum() {
        String tmpPackAgeNum = "";

        int tmppackage = localPackAgeNum+ packAgeNum;
        tmppackage++;
        if (tmppackage < 10) {
            tmpPackAgeNum = "000" + tmppackage;
        } else if (tmppackage >= 10 && tmppackage < 100) {
            tmpPackAgeNum = "00" + tmppackage;
        } else if (tmppackage >= 100 && tmppackage < 1000) {
            tmpPackAgeNum = "0" + tmppackage;
        }
        String goos = convertTimestamp2Date(System.currentTimeMillis(), "MMdd");
        goodsNum = goos + tmpPackAgeNum;
        et_goods_num.setText(goodsNum);
    }

    private void initScaner() {
        btn_ok_in.setBackgroundColor(getResources().getColor(R.color.unenabled));
        mQrCodeFinderView.setScanText("识别订单中...");
        et_goods_num.setText("");
        et_order_name.setText("");
        et_order_num.setText("");
        et_phone_num.setText("");
        et_address_num.setText("");
        et_phone_name.setText("");
        showTestBitmap(false, null);
        initScan();
    }

    private void showBtnStatus() {
        if (checkIsInputSuc()) {
            btn_ok_in.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        } else {
            btn_ok_in.setBackgroundColor(getResources().getColor(R.color.unenabled));
        }
    }


    /**
     * 绑定代办点扫描
     * @param bean
     */
    private void setEtTag3Content(OrderScanerDataBean.DataBean bean){
        et_order_name.setText(bean.getCompany());
        et_order_num.setText(bean.getOrderId());
        et_address_num.setText(bean.getDeliveryPhone());
        et_phone_name.setText(bean.getNickName());
        et_ex_ps_name.setText(bean.getUserName());

    }

    private void okScanerNext() {
        if (!checkIsInputSuc()) {
            return;
        }
        if(tag == 1){
            if(!Utils.isPhone(address)){
                Utils.toast(this,"请输入放置地址正确手机号!");
                return;
            }
        }
        boolean isCheck = false;
        for (ScanBean bean : scanList) {
            if(bean.getOrderId().equals(orderNum)){
                isCheck = true;
                break;
            }
        }
        //判断是否重复
        if(isCheck){
            Utils.toast(this,"订单重复入库");
            return;
        }

        scanList.add(new ScanBean(orderNum,userPhoneNum,address,userName,orderComName));
        SharedPreferencesUtil.getInstance().putSP(userPhoneNum, userName);
        if(tag == 1 || tag == 2){
            packAgeNum++;
            //保存快递件数
            SharedPreferencesUtil.getInstance().putSP("localPackAgeNum",(localPackAgeNum+packAgeNum)+"");
        }
        initScaner();
        showPackAgeNum();


    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        showBtnStatus();
    }

    /***
     * 入库
     */
    private void inPackage(){

        String token = SharedPreferencesUtil.getInstance().getSP("token");
        String listJson = new Gson().toJson(scanList);
        Log.i("SamTam",listJson);
        int isSmms = switch_is_smms.isChecked()?2:1;
        Utils.getInstance().post("manager/order/add?smss="+isSmms,listJson,token, new HTTPCallBack() {
            @Override
            public void Succ(String res) {
                try {
                    JSONObject jsonObject = new JSONObject(res);
                    int status = jsonObject.getInt("code");
                    boolean booleanSt = jsonObject.getBoolean("boolean");
                    if(status == 200){
                        scanList.clear();
                        Utils.toast(ScanerMainActivity.this,"扫描入库成功!");
                    }else {
                        String message = jsonObject.getString("message");
                        Utils.toast(ScanerMainActivity.this,"扫描入库失败!");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Utils.toast(ScanerMainActivity.this,"扫描入库失败!");
                }

            }

            @Override
            public void Fail(String errorStr) {
                Utils.toast(ScanerMainActivity.this,"扫描入库失败!");
            }
        });
    }

    /***
     * 代办点查询包裹状态
     * @param orderNum
     */
    private void getOrderStatus(String orderNum) {
        Map<String, String> parms = new HashMap<>();
        parms.put("orderId", orderNum);
        String token = SharedPreferencesUtil.getInstance().getSP("token");
        Utils.getInstance().post("/manager/order/scan",new Gson().toJson(parms),token, new HTTPCallBack() {
            @Override
            public void Succ(String res) {
                log(res);
                Gson gson = new Gson();
                OrderScanerDataBean orderScanerDataBean = gson.fromJson(res, OrderScanerDataBean.class);
                if (orderScanerDataBean != null && orderScanerDataBean.getCode() == 200) {
                    //绑定数据
                    packAgeNum = orderScanerDataBean.getSize();
                    showPackAgeNum();
                    setEtTag3Content(orderScanerDataBean.getData());

                }else {
                    Utils.toast(ScanerMainActivity.this,"暂无快递信息");
                }
            }

            @Override
            public void Fail(String errorStr) {

            }
        });
    }

    /***
     * 快递员扫描 代办点 同时扫描
     * @param orderNum
     */
    private void getOrderCom(String orderNum) {
        //1快递员 2代办点 3同时使用
        if (tag == 1) {
            Map<String, String> parms = new HashMap<>();
            parms.put("orderId", orderNum);
            String token = SharedPreferencesUtil.getInstance().getSP("token");
            Utils.getInstance().post("order/ordercompany", new Gson().toJson(parms), token, new HTTPCallBack() {
                @Override
                public void Succ(String res) {
                    log(res);
                    Gson gson = new Gson();
                    OrderCompanyBean orderCompanyBean = gson.fromJson(res, OrderCompanyBean.class);
                    if (orderCompanyBean != null && orderCompanyBean.getCode() == 200) {
                        ExBean ex = gson.fromJson(orderCompanyBean.getData(), ExBean.class);
                        et_order_name.post(() -> showExListDialog(ex));
                    }
                }

                @Override
                public void Fail(String errorStr) {

                }
            });
        }else{
            getOrderStatus(orderNum);
        }
    }

    private void log(String msg){
        Log.i("SamTam",msg);
    }
}
